
//
//  StatusPictureView.swift
//  WeoboWithSteveLi
//
//  Created by SteveLi on 2017/10/12.
//  Copyright © 2017年 李军桦. All rights reserved.
//

import UIKit
import SDWebImage
//照片之间的间距
let StatusPictureViewItemMargin: CGFloat = 8
//可重用标识符
let StatusPictureCellID = "StatusPictureCellID"
/// 配图视图
class StatusPictureView: UICollectionView {
    /// 微博视图模型
    var viewModel: StatusViewModel? {
        didSet {
            //自动计算大小 
            sizeToFit()
            //刷新数据
            reloadData()
        }
    }
    override func sizeThatFits(_ size: CGSize) -> CGSize {
        return calcViewSize()
    }
    
    //MARKL： -构造函数
    init() {
        let layout = UICollectionViewFlowLayout()
        //设置间距 默认 itemSize 是 50 * 50
        layout.minimumInteritemSpacing = StatusPictureViewItemMargin
        layout.minimumLineSpacing = StatusPictureViewItemMargin
        
        
        super.init(frame: CGRect.zero, collectionViewLayout: layout)
        //backgroundColor = UIColor(white: 0.8, alpha: 1.0)
        backgroundColor = UIColor.white
        //设置数据源 -- 自己当自己的数据源
        //应用场景：自定义视图的小框架
        dataSource = self
        //注册可重用 cell
        register(StatusPictureViewCell.self, forCellWithReuseIdentifier: StatusPictureCellID)
    }
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
}

extension StatusPictureView: UICollectionViewDataSource {
    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        return viewModel?.thumbnailUrls?.count ?? 0
    }
    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        let cell = collectionView.dequeueReusableCell(withReuseIdentifier: StatusPictureCellID, for: indexPath) as! StatusPictureViewCell
        cell.imageURL = viewModel?.thumbnailUrls![indexPath.item] as URL?
        return cell
    }
}

//MARK: -计算大小
extension StatusPictureView {
    //计算视图大小
    func calcViewSize() -> CGSize {
        //1.准备
        //每行的照片数量
        let rowCount : CGFloat = 3
        //最大宽度
        let maxWidth = UIScreen.main.bounds.width - 2 * StatusCellMargin
        let itemWidth = (maxWidth - 2 * StatusPictureViewItemMargin) / rowCount
        //2.设置 layout 的itemSize
        let layout = collectionViewLayout as! UICollectionViewFlowLayout
        layout.itemSize = CGSize(width: itemWidth, height: itemWidth)
        //3.获取图片数量
        let count = viewModel?.thumbnailUrls?.count ?? 0
        //计算
        //1.没有图片
        if count == 0 {
            return CGSize.zero
        }
        //2>1张图片
        if count == 1 {

            var size = CGSize(width: 150, height: 120)
            //利用SDWebImage 检查本地缓存图像 - key 就是url的完整字符串
            if let key = viewModel?.thumbnailUrls?.first?.absoluteString{
//                     let image = SDWebImageManager.shared().imageCache?.imageFromDiskCache(forKey: key)
//                    size = (image?.size)!
                if let image = SDWebImageManager.shared().imageCache?.imageFromDiskCache(forKey: key){
                    size = image.size
                }
         
                
            }
            //过窄处理 --针对长图
            size.width = size.width < 40 ? 40 : size.width
            //过宽的图片
            if size.width > 300 {
                let w: CGFloat = 300
                let h  = size.height * w  / size.width
                size = CGSize(width: w, height: h)
                
            }
            
            //内部图片的大小
            layout.itemSize = size
            //配图视图的大小
            return size
        }
        //3> 4张图片
        if count == 4 {
            let w = 2*itemWidth + StatusPictureViewItemMargin
            return CGSize(width: w, height: w)
        }
        //4> 其他图片,按照九宫格显示
        //计算出行数
        /*
             2 3
             5 6
             7 8 9
         */
        let row = CGFloat((count-1) / Int(rowCount) + 1)
        let h = row * itemWidth + (row - 1) * StatusPictureViewItemMargin
        let w = rowCount * itemWidth + (rowCount - 1) * StatusPictureViewItemMargin
        return CGSize(width: w, height: h)
    }
    
}
//微博配图cell
class StatusPictureViewCell: UICollectionViewCell {
    var imageURL: URL? {
        didSet{
            iconView.sd_setImage(with: imageURL,
                                 placeholderImage: nil,
                                 options: SDWebImageOptions.refreshCached,
                                 completed: nil)
        }
    }
    
    //MARK: -构造函数
   override init(frame:CGRect) {
        super.init(frame: frame)
        setupUI()
    }
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    func setupUI() {
        //1.添加控件
        contentView.addSubview(iconView)
        //2.设置布局 - 提示因为cell会变化，不同的cell 大小不能一样
        iconView.snp.makeConstraints { (make) in
            make.edges.equalTo(contentView.snp.edges)
        }
        iconView.frame = bounds
        
    }
    
    //MARK: --懒加载控件
    lazy var iconView: UIImageView = {
       let iv = UIImageView()
        //设置填充模式
        iv.contentMode = UIViewContentMode.scaleAspectFit
        //需要裁切图片
        iv.clipsToBounds = true
        return iv
    }()
}

